package com.example.listener;

import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 邮件消息监听器，监听RabbitMQ的mail队列
 * 当有消息发送到该队列时，根据消息内容发送不同类型的邮件
 * 实现了消息异步发送，提高系统响应性能
 *
 * @auth shanyue
 * @date 2025年06月23日10:16
 */
@Component
@RabbitListener(queues = "mail")
public class MailQueueListener {

    @Resource
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String username;

    /**
     * RabbitMQ消息处理方法
     * 当mail队列接收到消息时触发，提取邮件内容并发送相应邮件
     * @param data  消息内容
     */
    @RabbitHandler
    public void sendMailMessage(Map<String, Object> data) {
        String email = (String) data.get("email");
        Integer code = (Integer) data.get("code");
        String type = (String) data.get("type");
        SimpleMailMessage message = switch (type) {
            case "register" -> createMessage("欢迎注册本平台",
                    "您的邮件注册验证码为: " + code + ",有效时间3分钟，为了保障您的安全，请勿向他人泄露验证码信息。",
                    email);
            case "reset" -> createMessage("您的密码重置邮件",
                    "您好，您正在进行密码重置操作，验证码为" + code + ",有效时间3分钟，如非本人操作，请无视。",
                    email);
            default -> null;
        };

        if(message == null){
            return;
        }
        sender.send(message);

    }


    /**
     * 创建邮件对象
     * @param title 邮件主题
     * @param content   邮件正文内容
     * @param email 收件人邮箱地址
     * @return  构建的SimpleMailMessage对象
     */
    private SimpleMailMessage createMessage(String title, String content, String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);
        message.setText(content);
        message.setTo(email);
        message.setFrom(username);
        return message;
    }

}
